package frame.laxcen.loop.demo;

import frame.laxcen.loop.BaseLoopReader;
import frame.util.ByteArrayUtil;
import frame.util.ByteUtil;
import frame.util.Ref;

import java.util.function.Supplier;

public class LooperReader_Demo_4 extends BaseLoopReader {

    private Ref<Integer> cnt;

    @Override
    protected String loop(Ref<String> pc) {

        // 将更新和判断的逻辑抽象成 Supplier

        final Supplier<String> effect = () -> {

            cnt.swap(cnt.get() + 1);

            return cnt.get() == 2 ? pc.swap("pid-loop-end").get() : pc.swap("pid").get();
        };

        switch(pc.get()) {

            case "loop-begin":

                readU8("FrameHeader", ByteArrayUtil::toHexString);
                readU16("ControlWord", ByteArrayUtil::toHexString);
                readU16("DataLength", (bs) -> "" + ByteUtil.byteArrayToInt(bs));

                cnt = Ref.of(0);

            case "pid":

                // 实现一个 if 语意 读取任意 2 个pid后跳出循环
                if(readP16("Pid1", (byte) 0x01, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return effect.get();

                if(readP16("Pid2", (byte) 0x02, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return effect.get();

                if(readP16("Pid3", (byte) 0x03, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return effect.get();

                if(readP16("Pid4", (byte) 0x04, (bs) -> "" + ByteUtil.byteArrayToInt(bs)))
                    return effect.get();

            case "pid-loop-end":

                pc.swap("pid-loop-end");
        }

        return pc.swap("loop-end").get();
    }
}
